import * as express from 'express';
import * as  mock from 'mockjs';

import { Service } from './service';
import { Interface, Project } from './interface';
import { Event } from './event';
import { mockSetting } from './mock-setting';


export class Server {

  public startServer() {
    const app = express();
    const port = 3008;

    app.use(express.json());// 添加json解析
    app.use(express.urlencoded({ extended: false }));

    app.post('/api/project', async (req, res) => {
      const service = new Service();
      await service.addProject(req.body as Project);
      const event = Event.getSingle();
      event.emit("project-refresh");
      res.json({
        success: true,
      });
    });

    app.post('/api/interface', async (req, res) => {
      const service = new Service();
      await service.addInterface(req.body as Interface);
      const event = Event.getSingle();
      event.emit("project-refresh");
      res.json({
        success: true,
      });
    });

    app.get('/api/projects', async (req, res) => {
      const service = new Service();
      const data: Project[] = await service.queryProjects();
      res.json({
        success: true,
        data,
      });
    });

    app.get('/api/mock/:projectCode/*', async (req, res) => {

      const { "0": url, projectCode } = req.params;
      const service = new Service();
      const data = await service.queryInterfaceByUrl(projectCode, url);

      const obj = data.fields.reduce((prev: any, cur: any) => {
        if (mockSetting[cur.type]) {
          prev = { ...prev, ...mockSetting[cur.type](cur) };
        }
        return prev;
      }, {});

      let mockData: any;
      if (data.dataType === "object") {
        mockData = mock.mock(obj);
      } else {
        mockData = mock.mock({
          [`list|${data.arrayMinLength}-${data.arrayMaxLength}`]: [obj]
        }).list;
      }
      if (data.delay && data.delay > 0) {
        setTimeout(() => {
          res.json(mockData);
        }, data.delay);
      } else {
        res.json(mockData);
      }
    });


    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`);
    });
  }
}


